package com.webSite.demo.cy.downBook;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.filechooser.FileSystemView;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.hutool.core.io.file.FileWriter;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;

public class BookDown {

	private String srcLink ;
	private String[] book;
	private List<String> bookList;
	private static String writeSrc = null;
	
	static {
		FileSystemView fsv = FileSystemView.getFileSystemView();
		File com=fsv.getHomeDirectory();    //这便是读取桌面路径的方法了
		writeSrc = com.getPath();
	}
	
	public BookDown() {
		super();
	}

	public BookDown(String srcLink) {
		super();
		this.srcLink = srcLink;
	}

	public BookDown(String[] book) {
		super();
		this.book = book;
		for (String string : book) {
			getDownWebSrc(string);
		}
	}

	public BookDown(List<String> bookList) {
		super();
		this.bookList = bookList;
		for (String string : bookList) {
			getDownWebSrc(string);
		}
	}

	/**
	 * 获取相关网站的下载模板
	* @Title: getDownWebSrc  
	* @param @param srclink2    参数  
	* @return void    返回类型  
	* @throws
	 */
	public void getDownWebSrc(String srclink2) {
		if(StringUtils.isBlank(srcLink)) {
			srcLink = srclink2;
		}
		switch(getUri(srcLink)){
		case "https://www.kayege.com"://卡夜阁
        	getKaYeLink(srclink2,false);
            break;
		case "https://m.kayege.com"://卡夜阁
        	getKaYeLink(srclink2,true);
            break;
        case "http://www.523xs.com"://523小说
        	getKaYeLink(srclink2,false);
        	break;
        case "http://www.dushuzu.com"://读书族
        	getDuShuZu(srclink2);
        	break;
        default:
            System.out.println("暂时没有可用的模板");
            break;
        }
	}
	
	public void getDownWebSrc(String srclink2,int chapter) {
		if(StringUtils.isBlank(srcLink)) {
			srcLink = srclink2;
		}
		switch(getUri(srcLink)){
		case "https://www.kayege.com"://卡夜阁
        	getKaYeLink(srclink2,false,chapter);
            break;
		case "https://m.kayege.com"://卡夜阁
        	getKaYeLink(srclink2,true,chapter);
            break;
        case "http://www.523xs.com"://523小说
        	getKaYeLink(srclink2,false,chapter);
        	break;
        case "http://www.dushuzu.com"://读书族
        	getDuShuZu(srclink2);
        	break;
        default:
            System.out.println("暂时没有可用的模板");
            break;
        }
	}
	
	/**
	 * 获得干净的域名
	* @Title: getUri  
	* @param @param url
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	private String getUri(String url) {
		String buildUri = new String();
		try {
			URI uri = new URI(url);
			buildUri = uri.getScheme()+"://"+uri.getHost();
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return buildUri;
	}
	
	/**
	 * 读书族解析(未完成)
	* @Title: getDuShuZu  
	* @Description: TODO()  
	* @param @param link    参数  
	* @return void    返回类型  
	* @throws
	 */
	private static void getDuShuZu(String link) {
		String content = HttpUtil.get(link);
		
		Document doc = Jsoup.parse(content);
		Elements links = doc.body().select("#page-header .clearfix.dirconone ul li a");
		String bName = doc.body().select("#page-header .dirwraps h1").text();
		
		System.out.println(bName);
		for (Element l : links) {
			String linkHref = l.attr("href");
			String linkText = l.text();
			getWebGifSrc("http://www.dushuzu.com"+linkHref,linkText);
		}
	}

	/**
	 * 下载网站gif图片(未完成)
	* @Title: getWebGifSrc  
	* @Description: TODO()  
	* @param @param link
	* @param @param title    参数  
	* @return void    返回类型  
	* @throws
	 */
	private static void getWebGifSrc(String link,String title) {
		String content = HttpUtil.get(link);
		Document doc = Jsoup.parse(content);
		Elements imgLink = doc.body().select("#BookText img");
		for (Element element : imgLink) {
			System.out.println(element);
		}
	}

	/**
	 * 获取网站下的链接
	* @Title: getLink  
	* @param @param a    参数  
	* @return void    返回类型  
	* @throws
	 */
	private void getKaYeLink(String link,boolean mobile,int chapter) {
		String content = HttpUtil.get(link);
		Document doc = Jsoup.parse(content);
		if(mobile) {
			Elements links = doc.body().select(".bd a");
			String bName = doc.body().select(".hd h2").text().replaceFirst("章节列表", "");
			System.out.println(bName);
			int i=1;
			for (Element element : links) {
				String linkText = element.text();
				if(!linkText.startsWith("第")) {
					linkText = "第"+linkText;
				}
				if(i>chapter) {
					getMContent(element.attr("href"),linkText,bName);
				}
				System.out.println(linkText+"   章节："+i);
				i++;
			}
			
		}else {
			Elements links = doc.body().select("#list a");
			String bName = doc.body().select("#info h1").text();
			System.out.println(bName);
			for (Element l : links) {
				String linkHref = l.attr("href");
				String linkText = l.text();
				getPCLinkContent(linkHref,linkText,bName);
			}
		}
		
	}
	
	private void getKaYeLink(String link,boolean mobile) {
		String content = HttpUtil.get(link);
		Document doc = Jsoup.parse(content);
		if(mobile) {
			Elements links = doc.body().select(".bd a");
			String bName = doc.body().select(".hd h2").text().replaceFirst("章节列表", "");
			System.out.println(bName);
			int i=1;
			for (Element element : links) {
				String linkText = element.text();
				if(!linkText.startsWith("第")) {
					linkText = "第"+linkText;
				}
				getMContent(element.attr("href"),linkText,bName);
				System.out.println(linkText+"   章节："+i);
				i++;
			}
			
		}else {
			Elements links = doc.body().select("#list a");
			String bName = doc.body().select("#info h1").text();
			System.out.println(bName);
			for (Element l : links) {
				String linkHref = l.attr("href");
				String linkText = l.text();
				getPCLinkContent(linkHref,linkText,bName);
			}
		}
		
	}

	/**
	 * 获取pc链接文本
	* @Title: getLinkContent  
	* @param @param linkHref
	* @param @param linkText
	* @param @param bookName    参数  
	* @return void    返回类型  
	* @throws
	 */
	private void getPCLinkContent(String linkHref,String linkText,String bookName) {
		String content = getPcHttp(linkHref);
		Document doc = Jsoup.parse(content);
		Elements links = doc.body().select("#read p");
		
		List<String> first = new ArrayList<String>();
		first.add(linkText);//标题
		
		if(isAdd(doc.body().ownText())) {
			first.add(doc.body().ownText());
		}
		
		for (Element element : links) {
			if(isAdd(element.text())) {
				if(element.text().contains("(第1/2页)，请点击下一页继续阅读。")) {
					first.addAll(getPcNextLink(linkHref));
				}else {
					first.add(element.text());
				}
			}
		}
		
		FileWriter writer = new FileWriter(writeSrc+"\\"+bookName+".txt");
		writer.appendLines(first);
	}
	
	
	/**
	 * 获取手机端的文本
	* @Title: getMContent  
	* @Description: TODO()  
	* @param @param linkHref
	* @param @return    参数  
	* @return List<String>    返回类型  
	* @throws
	 */
	private void getMContent(String linkHref,String linkText,String bookName) {
		String content = getMHttp(getMlinkAndNext(linkHref, false));
		
		Document doc = Jsoup.parse(content);
		Elements links = doc.body().select(".page-content p");
		
		List<String> first = new ArrayList<String>();
		first.add(linkText);
		
		for (Element element : links) {
			if(isAdd(element.text())) {
				if(element.text().contains("(第1/2页)，请点击下一页继续阅读。")) {
					first.addAll(getMNextContent(linkHref));
				}else {
					first.add(element.text());
					
				}
			}
		}

		FileWriter writer = new FileWriter(writeSrc+"\\"+bookName+".txt");
		writer.appendLines(first);
	}

	/**
	 * 手机端下一页
	* @Title: getMNextContent  
	* @param @param linkHref
	* @param @return    参数  
	* @return List<String>    返回类型  
	* @throws
	 */
	private List<String> getMNextContent(String linkHref) {
		String nextContent = getMHttp(getMlinkAndNext(linkHref, true));
		
		Document nextdoc = Jsoup.parse(nextContent);
		Elements nextps = nextdoc.body().select(".page-content p");
		
		List<String> first = new ArrayList<String>();
		for (Element element2 : nextps) {
			if(isAdd(element2.text())) {
				first.add(element2.text());
			}
		}
		return first;
	}

	/**
	 * 下一页的内容
	* @Title: getNextLink  
	* @param @param link
	* @param @return    参数  
	* @return List<String>    返回类型  
	* @throws
	 */
	private List<String> getPcNextLink(String link) {
		String nextLink = link.replaceFirst(srcLink, "").replace(".html", "");
		
		StringBuilder builder = new StringBuilder(srcLink);
		builder.append(nextLink).append("_2.html");
		nextLink = builder.toString();
		
		String content = getPcHttp(nextLink);
		
		Document doc = Jsoup.parse(content);
		Elements links = doc.body().select("#read p");
		
		List<String> first = new ArrayList<String>();
		for (Element element : links) {
			if(isAdd(element.text())) {
				first.add(element.text());
			}
		}
		
		return first;
	}
	
	/**
	 * 模拟手机端的请求
	* @Title: getMHttp  
	* @Description: TODO()  
	* @param @param link
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	private String getMHttp(String link) {
		String content = HttpRequest.post(link)
			    .header(Header.COOKIE,"UM_distinctid=16443dc3b8e27c-0a03528c1e183c-61131b7e-13c680-16443dc3b8f2f9; Hm_lvt_848be1a5024c8d8b8651bf2ac8a92035=1535935046,1535935306,1535935310,1535936772; CNZZDATA1255969718=1479538000-1530145286-https%253A%252F%252Fwww.baidu.com%252F%7C1535943400; Hm_lpvt_848be1a5024c8d8b8651bf2ac8a92035=1535945078")
			    .header(Header.USER_AGENT,"User-Agent: Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_2 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B440 Safari/600.1.4")
			    .timeout(500000)//超时，毫秒
			    .execute().body();
		return content;
	}

	/**
	 * 模拟电脑端的请求
	* @Title: getPcHttp  
	* @Description: TODO()  
	* @param @param link
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	private String getPcHttp(String link) {
		String content = HttpRequest.post(link)
			    .header(Header.COOKIE,"UM_distinctid=16443dc3b8e27c-0a03528c1e183c-61131b7e-13c680-16443dc3b8f2f9; Hm_lvt_848be1a5024c8d8b8651bf2ac8a92035=1535935046,1535935306,1535935310,1535936772; CNZZDATA1255969718=1479538000-1530145286-https%253A%252F%252Fwww.baidu.com%252F%7C1535943400; Hm_lpvt_848be1a5024c8d8b8651bf2ac8a92035=1535945078")
			    .timeout(500000)//超时，毫秒
			    .execute().body();
		return content;
	}

	/**
	 * 符合规则的才可以添加
	* @Title: isAdd  
	* @param @param text
	* @param @return    参数  
	* @return boolean    返回类型  
	* @throws
	 */
	public static boolean isAdd(String text) {
		boolean flag = false;
		if(StringUtils.isNotBlank(text) && !StringUtils.equals(text, "暂时无内容,请稍后访问！") && !StringUtils.equals(text, "最新内容,请到卡夜阁阅读!") && !StringUtils.equals(text, "由于版权原因,无法阅读！")) {
			flag = true;
		}
		return flag;
	}
	
	/**
	 * 获取手机端的连接，false则获取下一页
	* @Title: getMlinkAndNext  
	* @Description: TODO()  
	* @param @param link
	* @param @param next
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	public String getMlinkAndNext(String link,boolean next) {
		String chapter = link.replaceFirst(srcLink, "").replace(".html", "");
		StringBuilder chapterLink = new StringBuilder();

		if(next) {
			chapterLink = new StringBuilder(srcLink.replace("www", "m"));
			chapterLink.append(chapter).append("_2.html");
		}else {
			chapterLink = new StringBuilder(link.replace("www", "m"));
		}
		
		return chapterLink.toString();
	}
	
	/**
	 * 
	* @Title: getPClink  
	* @Description: TODO()  
	* @param @param link
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	public String getPClink(String link) {
		String chapter = link.replaceFirst(srcLink, "").replace(".html", "");
		
		StringBuilder chapterLink = new StringBuilder(srcLink);
		chapterLink.append(chapter).append("_2.html");
		
		return chapterLink.toString();
	}

	public String getSrcLink() {
		return srcLink;
	}

	public void setSrcLink(String srcLink) {
		this.srcLink = srcLink;
	}

	public String[] getBook() {
		return book;
	}

	public void setBook(String[] book) {
		this.book = book;
	}

	public List<String> getBookList() {
		return bookList;
	}

	public void setBookList(List<String> bookList) {
		this.bookList = bookList;
	}
	
}
